package com.hh.controller;

import com.hh.anno.Log;
import com.hh.entity.SysMenu;
import com.hh.service.SysMenuService;
import com.hh.vo.MenuAndAuths;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @author 辉辉 2022/8/15 20:18
 */
@Api("后台菜单接口")
@RestController
@RequestMapping("/sys/menu")
public class MenuController {
    @Resource
    private SysMenuService sysMenuService;

    /**
     * 加载树菜单和权限的接口
     * @return
     */
    @GetMapping("/nav")
    @ApiOperation(value = "加载用户菜单和权限的接口")
//    @PreAuthorize("hasAuthority('')")
    @Log(operation = "加载用户菜单和权限的接口")
    public ResponseEntity<?> loadMenuAndAuths() {
        // 1. 获取当前用户ID 由于实体类讲username 改成了userId
        String userId = SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString();
        // 查询菜单
        List<SysMenu> menus = sysMenuService.loadUserMenu(userId);
        // 获取权限
        Collection<? extends GrantedAuthority> authorities = SecurityContextHolder.getContext().getAuthentication().getAuthorities();
        // 转换一个权限
        List<String> auths = new ArrayList<>();
        authorities.forEach(authoritie -> auths.add(authoritie.getAuthority()));
        // 创建返回值
        MenuAndAuths menuAndAuths = new MenuAndAuths();
        menuAndAuths.setMenuList(menus);
        menuAndAuths.setAuthorities(auths);
        return ResponseEntity.ok(menuAndAuths);
    }
}
